//
//  SignInViewController.m
//  1gene
//
//  Created by 1jiyin on 16/3/21.
//  Copyright © 2016年 1jiyin. All rights reserved.
//
//************签到************
#define SNOW_IMAGENAME         @"snow"

#define IMAGE_X                arc4random()%(int)Main_Screen_Width
#define IMAGE_ALPHA            ((float)(arc4random()%10))/10
#define IMAGE_WIDTH            arc4random()%20 + 10
#define PLUS_HEIGHT            Main_Screen_Height/25
#import "SignInViewController.h"

@interface SignInViewController ()

@property(nonatomic,copy)NSTimer *myTimer;

@property(nonatomic,copy)UIButton *signInBtn;

@property(nonatomic,copy)UILabel *moneyLab;

@property(nonatomic,copy)UIButton *signInDaysBtn;


@end

@implementation SignInViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor=[UIColor whiteColor];
    [self createNavigation];
    [self createUI];
    [self getSignInHttpData];
    [self startSignInAnimation];
    // Do any additional setup after loading the view.
}
//显示奖励
-(void)showAward{
    NSInteger score=[[NSString stringWithFormat:@"%@",_dataDic[@"credits_change"]] integerValue];
    if (score==0) {
        
    }else if (score==4){
        [self.view showTiShiMessage:@"已签到7天，奖励3分"];
    }else if (score==11){
        [self.view showTiShiMessage:@"已签到1个月，奖励10分"];
    }else if (score==51){
        [self.view showTiShiMessage:@"已签到3个月，奖励50分"];
    }
}

-(void)startSignInAnimation
{
    _imagesArray = [[NSMutableArray alloc] init];
    for (int i = 0; i < 20; ++ i) {
        UIImageView *imageView = [[UIImageView alloc] initWithImage:IMAGENAMED(SNOW_IMAGENAME)];
        float x = IMAGE_WIDTH;
        imageView.frame = CGRectMake(IMAGE_X, -30, x, x);
        imageView.alpha = IMAGE_ALPHA;
        [self.view addSubview:imageView];
        [_imagesArray addObject:imageView];
    }
    if (_myTimer==nil) {
         _myTimer=[NSTimer scheduledTimerWithTimeInterval:.3 target:self selector:@selector(makeSnow) userInfo:nil repeats:YES];
    }
   
}

static int i = 0;
static int number=0;
- (void)makeSnow
{
    number++;
    if (number==50) {
        [_myTimer invalidate];
        _myTimer=nil;
        number=0;
        i=0;
        [_imagesArray removeAllObjects];
    }
    i = i + 1;
    if ([_imagesArray count] > 0) {
        UIImageView *imageView = [_imagesArray objectAtIndex:0];
        imageView.tag = i;
        [_imagesArray removeObjectAtIndex:0];
        [self snowFall:imageView];
    }
    
}

- (void)snowFall:(UIImageView *)aImageView
{
    [UIView beginAnimations:[NSString stringWithFormat:@"%ld",aImageView.tag] context:nil];
    [UIView setAnimationDuration:6];
    [UIView setAnimationDelegate:self];
    aImageView.frame = CGRectMake(aImageView.frame.origin.x, Main_Screen_Height, aImageView.frame.size.width, aImageView.frame.size.height);
    NSLog(@"%@",aImageView);
    [UIView commitAnimations];
}

- (void)addImage
{
}

- (void)animationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context
{
    UIImageView *imageView = (UIImageView *)[self.view viewWithTag:[animationID intValue]];
    float x = IMAGE_WIDTH;
    imageView.frame = CGRectMake(IMAGE_X, -30, x, x);
    [_imagesArray addObject:imageView];
}

-(void)createUI
{
    UIImageView *imgView=[[UIImageView alloc]initWithFrame:CGRectMake(0, 20+44, self.view.frame.size.width, self.view.frame.size.height-20-44)];
    imgView.image=[UIImage imageNamed:@"qiandao_1"];
    [self.view addSubview:imgView];
    
    //签到
    UIButton *signInBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    signInBtn.frame=CGRectMake((self.view.frame.size.width-260)/2.0, self.view.frame.size.height/2.0+40, 260, 60);
    [signInBtn setBackgroundImage:[UIImage imageNamed:@"signIn_btn2"] forState:UIControlStateNormal];
    [signInBtn setTitle:@"未签到" forState:UIControlStateNormal];
    signInBtn.userInteractionEnabled=NO;
    [self.view addSubview:signInBtn];
    _signInBtn=signInBtn;
    
    //我的健康币
    UILabel *myLab=[[UILabel alloc]initWithFrame:CGRectMake((self.view.frame.size.width-50)/2.0-70, CGRectGetMaxY(signInBtn.frame), 70, 50)];
    myLab.text=@"我的健康币";
    myLab.font=[UIFont systemFontOfSize:12];
    myLab.textColor=[UIColor whiteColor];
    [self.view addSubview:myLab];
    
    //钱币
    UIImageView *qianbiImageView=[[UIImageView alloc]initWithFrame:CGRectMake((self.view.frame.size.width-50)/2.0, CGRectGetMaxY(signInBtn.frame), 50, 50)];
    qianbiImageView.image=[UIImage imageNamed:@"signIn_btn3"];
    [self.view addSubview:qianbiImageView];
    
    //健康币的数量
    UILabel *moneyNumber=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(qianbiImageView.frame), qianbiImageView.frame.origin.y, 170, 50)];
    moneyNumber.text=[NSString stringWithFormat:@"%.1f枚",_myScore];
    moneyNumber.font=[UIFont systemFontOfSize:20];
    moneyNumber.textColor=[UIColor redColor];
    [self.view addSubview:moneyNumber];
    _moneyLab=moneyNumber;
    
    
    //健康币的说明
    UILabel *explainLab=[[UILabel alloc]initWithFrame:CGRectMake(myLab.frame.origin.x+16, CGRectGetMaxY(myLab.frame), CGRectGetMaxX(moneyNumber.frame)-myLab.frame.origin.x, 40)];
    explainLab.text=@"100枚健康币=人民币1元";
    explainLab.font=[UIFont systemFontOfSize:12];
    explainLab.textColor=[UIColor whiteColor];
    //explainLab.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview:explainLab];
    //已经签到
    UILabel *haveSignInDays=[[UILabel alloc]initWithFrame:CGRectMake(myLab.frame.origin.x+36, CGRectGetMaxY(explainLab.frame), 60, 40)];
    haveSignInDays.text=@"签到";
    haveSignInDays.font=[UIFont systemFontOfSize:12];
    haveSignInDays.textColor=[UIColor whiteColor];
    haveSignInDays.frame=CGRectMake(haveSignInDays.frame.origin.x, haveSignInDays.frame.origin.y, [self calculateWidthWithLable:haveSignInDays]+5, haveSignInDays.frame.size.height);
    //haveSignInDays.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview:haveSignInDays];
    
    //签到的天数
    UIButton *signInDaysBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    signInDaysBtn.frame=CGRectMake(CGRectGetMaxX(haveSignInDays.frame), CGRectGetMaxY(explainLab.frame), 50, 40);
    [signInDaysBtn setBackgroundImage:[UIImage imageNamed:@"signIn_btn5"] forState:UIControlStateNormal];
    [signInDaysBtn setTitle:[NSString stringWithFormat:@"0"] forState:UIControlStateNormal];
    [signInDaysBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    signInDaysBtn.contentEdgeInsets=UIEdgeInsetsMake(12, 10, 0, 10);
    signInDaysBtn.userInteractionEnabled=NO;
    [self.view addSubview:signInDaysBtn];
    _signInDaysBtn=signInDaysBtn;
    
    
    //天
    UILabel *dayLab=[[UILabel alloc]initWithFrame:CGRectMake(CGRectGetMaxX(signInDaysBtn.frame), signInDaysBtn.frame.origin.y, 25, 40)];
    dayLab.text=@"天!";
    dayLab.font=[UIFont systemFontOfSize:12];
    dayLab.textColor=[UIColor whiteColor];
    dayLab.textAlignment=NSTextAlignmentCenter;
    [self.view addSubview:dayLab];
    
    
}
-(void)createNavigation
{
    self.navigationController.navigationBar.barTintColor=[UIColor colorWithRed:84/255.0 green:199/255.0 blue:222/255.0 alpha:1];
    //返回
    UIButton *leftBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame=CGRectMake(0, 0, 25, 25);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"left_back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    
    //标题
    UILabel *title=[[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 44)];
    title.text=@"签到中心";
    title.font=[UIFont systemFontOfSize:22];
    title.textAlignment=NSTextAlignmentCenter;
    title.textColor=[UIColor whiteColor];
    self.navigationItem.titleView=title;
    
    //完成按钮
    UIButton *rightBtn=[UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn.frame=CGRectMake(0, 0, 50, 44);
    [rightBtn setTitle:@"积分说明" forState:UIControlStateNormal];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    rightBtn.titleLabel.font=[UIFont systemFontOfSize:12];
    [rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem=[[UIBarButtonItem alloc]initWithCustomView:rightBtn];
}
//返回上一页
-(void)leftBtnClick:(UIButton *)sender
{
    self.navigationController.navigationBar.hidden=YES;
    self.tabBarController.tabBar.hidden=NO;
    [self.navigationController popViewControllerAnimated:YES];
}
//积分说明
-(void)rightBtnClick:(UIButton *)sender
{
    ScoreExplainViewController *vc=[[ScoreExplainViewController alloc]init];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//根据文字计算宽度和高度
-(CGFloat)calculateWidthWithLable:(UILabel *)label
{
    CGSize size=[label.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:label.font,NSFontAttributeName, nil]];
    return size.width;
}

//签到
-(void)getSignInHttpData
{
    AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    [self.view isLoading:YES];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager POST:[NSString stringWithFormat:@"%@%@",SignIn,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"login=======%@",dic);
        if (dic) {
            _dataDic=[NSDictionary dictionaryWithDictionary:dic];
            [self showAward];
            [self getUserInfo];
            dispatch_async(dispatch_get_main_queue(), ^{
                [_signInBtn setTitle:@"已签到" forState:UIControlStateNormal];
            });
            
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        [self.view showTiShiMessage:@"签到失败"];
        NSLog(@"error====%@",error.localizedDescription);
    }];
    
}


//获取用户信息
-(void)getUserInfo
{
    AFHTTPRequestOperationManager * manager=[AFHTTPRequestOperationManager manager];
    manager.requestSerializer=[AFHTTPRequestSerializer serializer];
    manager.responseSerializer=[AFHTTPResponseSerializer serializer];
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    NSString *token= [user objectForKey:@"token"];
    
    [manager GET:[NSString stringWithFormat:@"%@%@",UserInfo,token] parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [self.view isLoading:NO];
        NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"userInfo===%@",dic);
        if (dic) {
            dispatch_async(dispatch_get_main_queue(), ^{
                _myScore=[dic[@"user_profile"][@"credits"] floatValue];
                _moneyLab.text=[NSString stringWithFormat:@"%.1f枚",_myScore];
                if ([dic[@"all_sign"] isKindOfClass:[NSNull class]]) {
                    [_signInDaysBtn setTitle:[NSString stringWithFormat:@"0"] forState:UIControlStateNormal];
                }else{
                    [_signInDaysBtn setTitle:[NSString stringWithFormat:@"%ld",[dic[@"all_sign"] integerValue]+1] forState:UIControlStateNormal];
                }
            });
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.view isLoading:NO];
        NSLog(@"%@",error.localizedDescription);
    }];
    
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
